from django.contrib.auth import authenticate,login,logout
from django.shortcuts import render
from django.views.generic import View
from django.contrib.auth.models import User
from django import http
from django_redis import get_redis_connection
from django.contrib.auth.models import User
import re
import json
from django.core.mail import send_mail
from django.conf import settings
from PMSP.utils.email import generate_verify_code
from users.models import Address
from carts.utils import merge_cookie_redis_data

# 1,注册视图
class UserRegisterView(View):
    def get(self,request):
        return render(request,template_name='register.html')

    def post(self,request):
        # 1,获取参数
        username = request.POST.get("user_name")
        password = request.POST.get("pwd")
        password2 = request.POST.get("cpwd")
        mobile = request.POST.get("phone")
        sms_code = request.POST.get("msg_code")
        allow = request.POST.get("allow")

        # 2,校验短信验证码
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get(f"sms_code_{mobile}")
        if sms_code != redis_sms_code.decode():
            return render(request,template_name='register.html')

        # 3，为空校验，（还需要：密码长度校验，用户名校验，两次密码是否一致校验，手机号格式校验）
        if not all([username,password2,password,mobile,sms_code,allow]):
            return render(request,template_name='register.html')

        # 4，创建用户，并入库
        user = User.objects.create(
            username=username,
            password=password,
            mobile=mobile,
            first_name="zhang",
            last_name="ha"
        )

        # 4,1 密码加密存储
        user.set_password(password)
        user.save()

        # 5，返回响应
        return http.HttpResponseRedirect("/login")

# 2,检查用户名是否重复
class CheckUserNameView(View):
    def get(self,request,username):
        # 1,根据请求参数查询用户名是否存在
        count = User.objects.filter(username=username).count()

        # 2,返回响应
        return http.JsonResponse({"count":count})

# 3,检查手机号是否重复
class CheckPhoneView(View):
    def get(self,request,mobile):
        # 1,根据请求参数查询用户名是否存在
        count = User.objects.filter(mobile=mobile).count()

        # 2,返回响应
        return http.JsonResponse({"count": count})

# 4,登录视图
class UserLoginView(View):
    def get(self,request):
        return render(request,template_name='login.html')

    def post(self,request):

        # 1,获取参数
        username = request.POST.get("username")
        pwd = request.POST.get("pwd")
        remembered = request.POST.get("remembered")

        # 2，校验参数
        # 2，1 为空校验
        if not all([username,pwd]):
            return render(request,template_name='login.html')

        # 2，2 用户名格式校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return render(request,template_name='login.html')

        # 2，3 密码格式校验
        if not re.match(r'^[0-9A-Za-z]{8,20}$',pwd):
            return render(request,template_name='login.html')

        # 2，4 校验账号，密码正确性
        user = authenticate(request=request,username=username,password=pwd)
        if not user:
            return render(request, template_name='login.html')

        # 3，状态保持
        login(request=request,user=user)
        state_time = 0
        if remembered == "on":
            state_time = 3600*24*2
            request.session.set_expiry(state_time)
        else:
            request.session.set_expiry(state_time)

        # 4, 设置username的cookie信息并返回响应
        response = http.HttpResponseRedirect("/")
        response.set_cookie("username",user.username,max_age=state_time)

        # 5,合并cookie中的购物车数据
        response = merge_cookie_redis_data(request,user,response)

        return response

# 5,退出登录视图
class UserLogoutView(View):
    def get(self,request):
        # 1,清除session信息
        logout(request)

        # 2，清除cookie并重定向首页
        response = http.HttpResponseRedirect("/")
        response.delete_cookie("username")
        return response

# 6,用户中心
class UserCenterInfoView(View):
    def get(self,request):

        # 1,判断用户是否登录了,如果是匿名用户，直接返回首页
        if request.user.is_anonymous:
            return http.HttpResponseRedirect("/")

        # 2，如果用户登录了，不是匿名用户，那么我们返回用户中心页面
        content = {
            "username":request.user.username,
            "mobile":request.user.mobile,
            "email":request.user.email,
            "email_active":request.user.email_active
        }
        return render(request,template_name='user_center_info.html',context=content)

# 7,用户邮箱
class UserEmailView(View):
    def put(self,request):
        # 1,获取请求参数
        dict_data = json.loads(request.body.decode())
        email = dict_data.get("email")

        # 2,校验参数(还需要：邮箱格式校验等操作)
        if not email:
            return http.JsonResponse({"code":5000})

        # 3，发送邮件
        # send_mail(
        #     subject='PMSP Active Email',
        #     message="",
        #     from_email=settings.EMAIL_HOST_USER,
        #     recipient_list=[email],
        #     html_message=generate_verify_code(request.user,email)
        # )
        from PMSP.utils.celery_task.celery import send_verify_url
        send_verify_url.delay(email,generate_verify_code(request.user,email))

        # 4,返回响应
        return http.JsonResponse({"code":0})

    def get(self,request):
        # 1,获取参数
        token = request.GET.get("token")

        # 2,校验参数(为空校验)
        if not token:
            return http.HttpResponseForbidden("非法请求")

        dict_data = json.loads(token)

        # 3，设置邮箱并激活
        request.user.email = dict_data.get("email")
        request.user.email_active = True
        request.user.save()

        # 4,重新渲染用户中心
        return http.HttpResponseRedirect("/info")

# 8,用户地址页面
class UserAddressView(View):
    def get(self,request):
        # 1，查询当前用户的地址
        addresses = Address.objects.filter(user_id=request.user.id,is_delete=False).all()

        # 2，拼接数据渲染页面
        addresses_list = []
        for item in addresses:
            item_dict = {
                "title": item.title,
                "receiver": item.receiver,
                "province": item.province.name,
                "city": item.city.name,
                "district": item.district.name,
                "place": item.place,
                "mobile": item.mobile,
                "tel": item.tel,
                "email": item.email,
                "province_id":item.province_id,
                "city_id":item.city_id,
                "district_id":item.district_id,
                "id":item.id
            }
            addresses_list.append(item_dict)

        return render(request,template_name='user_center_site.html',context={"addresses":addresses_list})

# 9,新增地址
class UserAddressCreateView(View):
    def post(self,request):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        # 2,为空校验（还需要：校验收货人长度，省，市，区的id是否存在，手机号格式等。。。）
        if not all([title,receiver,province_id,city_id,district_id,place,mobile,tel,email]):
            return http.JsonResponse({"code":5000,"errmsg":"参数异常"})

        # 3，保存收货地址到数据库
        # Address.objects.create(user=request.user.id,title=title,....)
        dict_data["user"] = request.user
        new_address = Address.objects.create(**dict_data)

        # 4,返回响应
        address = {
            "title":title,
            "receiver":receiver,
            "province":new_address.province.name,
            "city":new_address.city.name,
            "district":new_address.district.name,
            "place":place,
            "mobile":mobile,
            "tel":tel,
            "email":email,
            "province_id": province_id,
            "city_id": city_id,
            "district_id": district_id,
            "id": new_address.id
        }
        return http.JsonResponse({"code":0,"address":address})

# 10,修改地址,删除地址
class UserAddressUpdateView(View):
    def put(self, request,address_id):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        # 2,为空校验（还需要：校验收货人长度，省，市，区的id是否存在，手机号格式等。。。）
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.JsonResponse({"code": 5000, "errmsg": "参数异常"})

        # 3,修改地址数据
        address = Address.objects.get(id=address_id)
        address.title = title
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()

        # 4,返回响应
        address = {
            "title": title,
            "receiver": receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": place,
            "mobile": mobile,
            "tel": tel,
            "email": email,
            "province_id": province_id,
            "city_id": city_id,
            "district_id": district_id,
            "id": address.id
        }
        return http.JsonResponse({"code": 0, "address": address})

    def delete(self,request,address_id):
        # 1,获取地址对象
        address = Address.objects.get(id=address_id)

        # 2,逻辑删除地址
        address.is_delete = True
        address.save()

        # 3,返回响应
        return http.JsonResponse({"code":0,"errmsg":"删除成功"})

# 11,设置默认地址
class UserAddressDefaultView(View):
    def put(self,request,address_id):
        # 1,设置用户默认地址
        request.user.default_address_id = address_id
        request.user.save()

        # 2,返回响应
        return http.JsonResponse({"code":0,"errmsg":"设置默认地址成功"})

# 12,设置地址标题
class UserAddressTitleView(View):
    def put(self,request,address_id):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")

        # 2,为空校验（真实：需要校验标题长度）
        if not title:
            return http.JsonResponse({"code":5000,"errmsg":"标题不能为空"})

        # 3，修改地址标题
        Address.objects.filter(id=address_id).update(title=title)
        # address.title = title
        # address.save()

        # 4,返回响应
        return http.JsonResponse({"code":0,"errmsg":"修改地址标题成功"})

# 13,修改密码
class UserChangePasswordView(View):
    def get(self,request):

        return render(request,template_name="user_center_pass.html")

    def post(self,request):
        # 1,获取参数
        old_pwd = request.POST.get("old_pwd")
        new_pwd = request.POST.get("new_pwd")
        new_cpwd = request.POST.get("new_cpwd")

        # 2,为空校验（真实：校验长度，校验密码组成,两次新密码是否一致）
        if not all([old_pwd,new_pwd,new_cpwd]):
            return render(request, template_name="user_center_pass.html")

        # 3,老密码正确性
        if not request.user.check_password(old_pwd):
            return render(request, template_name="user_center_pass.html")

        # 4,新老密码不一致校验
        if old_pwd == new_pwd or old_pwd == new_cpwd:
            return render(request, template_name="user_center_pass.html")

        # 5,新密码入库
        request.user.set_password(new_pwd)
        request.user.save()

        # 6,返回响应
        return http.HttpResponseRedirect("/login")